package com.hh.ListNodeQuestions;

/**
 * @Author hanghao
 * @Date 2023/6/28 14:23
 * @Version 1.0
 * 每K个一组 进行翻转链表                (递归函数系列)
 * Hard
 */

public class No25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0,head);
        ListNode pre = dummy;
        ListNode end = dummy;

        while(end.next != null) {
            for (int i = 0; i < k && end != null ; i++) {
                end = end.next;
            }
            if (end == null) break;
            ListNode start = pre.next;
            ListNode next = end.next;
            end.next = null;   //这一步我的理解是断开连接 为reverse方法做铺垫
            pre.next = reverse(start); //反转这一段  连接上前面
            start.next = next;         //将后面连起来
            pre = start;
            end = pre;
        }
        return dummy.next;
    }
    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

}
